//********************************************************************
// Pocket Podcasts - Desktop and mobile device podcast client
// Copyright (C) 2005, 2006 Wes Henderson <whenders@gmail.com> and
// Contributors
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
//********************************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;

namespace PocketPodcasts
{
    /// <summary>
    /// Windows mobile graphical user interface
    /// </summary>
	public partial class PpGui : Form
	{
		

		     // to hold audio file locations
        public string [] FileLoc;
        private Searcher searcher;
        // Data table and column names
        private bool UnderTest = false;
        private const string TableName = "TestTable";
        private const string NameCol = "Name";
        private const string CatCol = "Category";
        private const string DescCol = "Description";
        private const string RatCol = "Rating";
        private const string FileCol = "Location";
        private net.hlady.pocketpodcasts.ppWSDL WebFunc;
        private const int MaxKeywords = 10;
        private const string ErrKeywords = "Please enter up to ten search keywords.";
        private const String NameDescRow = "KeywordSearchDesktop_net_hlady_pocketpodcasts_NameDescRow";
		private const string DownloadedPodcastsListPath = @"\Storage Card\podcastlist.xml";
        public PpGui()
        {
            InitializeComponent();
          
            // Set up the very artificial sample DataSet with 
            // various types and values. 
            string applicationDirectory;
            System.Reflection.Assembly execAssem = System.Reflection.Assembly.GetExecutingAssembly();
            // Set up the application file name from the current assembly.
            string appFilePath = execAssem.GetModules()[0].FullyQualifiedName;
            applicationDirectory = System.IO.Path.GetDirectoryName(appFilePath);
            if (!applicationDirectory.EndsWith(@"\"))
            {
                applicationDirectory += @"\";
            }
        }

        ///<summary>
        ///   - Writes a podcast list to a XML file <br/>
        ///   - Parameter: MyList - List of podcasts <br/>
        /// Return true on success, false otherwise
        ///</summary>
        private bool WriteXml(PodcastList myList)
        {
            try
            {
                if (myList != null)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(PodcastList));
                    TextWriter tw = new StreamWriter(@"\Storage Card\podcastlist.xml");
                    serializer.Serialize(tw, myList);
                    tw.Close();
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }


		/////<summary>
		/////   - Test Create(Iteration 1) test case<br/>
		/////   - click handler for button2 (Test Create)<br/>
		/////   - For testing/debugging purposes.<br/>
		/////   - Test creating an xml file from data in PodcastList.<br/>
		/////</summary>
		//private void button2_Click(object sender, EventArgs e)
		//{

		//    PodcastList myList = new PodcastList();
		//    myList.AddItem(new PodcastInfo("This Week In Tech", "more eggs", "even more eggs", 10, @"\Storage Card\empty.mp3", "Episode 41: Seagate plant goes haywire"));
		//    myList.AddItem(new PodcastInfo("Engadget Podcast", "more milks", "even more milks", 10, @"\Storage Card\ending.mp3", "VOIP Phones and You"));
		//    myList.AddItem(new PodcastInfo("CNET Weekly Podcast", "is a murderer", "most wanted", 10, @"\Storage Card\ending.mp3", "Microsoft Fights EU Monopoly Claims"));
		//    myList.AddItem(new PodcastInfo("This Week In Tech", "more eggs", "even more eggs", 10, @"\Storage Card\empty.mp3", "Episode 42: Windows Vista Delayed"));
		//    myList.AddItem(new PodcastInfo("Engadget Podcast", "more milks", "even more milks", 10, @"\Storage Card\ending.mp3", "Some Phone Reviews and a Ultra Portable Review"));
		//    myList.AddItem(new PodcastInfo("CNET Weekly Podcast", "is a murderer", "most wanted", 10, @"\Storage Card\ending.mp3", "Weekly wrap-up: Apple makes announcement"));
		//    //Note: use triple quotations for filepath

		//    myList.SaveToXml(DownloadedPodcastsListPath);

		//    /*
		//    bool success = WriteXml(myList);
		//    if (success)
		//        MessageBox.Show("Valid Write Test Passed!");
		//    else
		//        MessageBox.Show("Valid Write Test Failed!");
		//    myList = null;
		//    success = WriteXml(myList);
		//    if (success)
		//        MessageBox.Show("Invalid Write Test Failed!");
		//    else
		//        MessageBox.Show("Invalid Write Test Passed!");*/

		//}

		/////<summary>
		/////   - Test Load (Iteration 1)
		/////   - click handler for button3 (Test Load)   <br/> 
		/////   - for testing/debugging purposes.<br/>
		/////   - Test loading data from xml file into DataTable.<br/>
		/////</summary>
		//private void button3_Click(object sender, EventArgs e)
		//{
		//    DisplayDownloadedPodcasts();

		//    /*
		//    if (success)
		//        MessageBox.Show("Valid Test Passed!");
		//    else
		//        MessageBox.Show("Valid Test Failed!");
		//    xmlLoc = @"\Storage Card\do_not_exist.xml";
		//    success = ReadXml(xmlLoc);
		//    if (success)
		//        MessageBox.Show("Invalid Test Failed!");
		//    else
		//        MessageBox.Show("Invalid Test Passed!");*/

		//}
		
        /// <summary>
        /// Loads UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PpGui_Load(object sender, EventArgs e)
        {
			/*if (UnderTest)
			{
				button2.Show();
				button3.Show();
				bntTestSearch.Show();
			}*/

			SmartUI.CustomListView view = new SmartUI.CustomListView();
			view.ShowDialog();
			//DisplayDownloadedPodcasts2();
        }

		/// <summary>
		/// Displays the list of downloaded/available podcasts for playback.
		/// </summary>
		private void DisplayDownloadedPodcasts()
		{
			PodcastList downloadedPodcasts = PodcastList.LoadFromXml(DownloadedPodcastsListPath);
			if (downloadedPodcasts != null && downloadedPodcasts.CountItem() > 0)
			{
				string tmpFile = Path.GetTempFileName();
				string html = downloadedPodcasts.ToMobileHTML();
				StreamWriter sw = File.AppendText(tmpFile);
				sw.Write(html);
				sw.Flush();
				sw.Close();

				webBrowser1.Navigate(new Uri(tmpFile));
			}
		}

		/// <summary>
		/// Displays the list of downloaded/available podcasts for playback.
		/// </summary>
		private void DisplayDownloadedPodcasts2()
		{
			PodcastList downloadedPodcasts = PodcastList.LoadFromXml(DownloadedPodcastsListPath);
			if (downloadedPodcasts != null && downloadedPodcasts.CountItem() > 0)
			{
				foreach (PodcastInfo info in downloadedPodcasts.PodcastInfo)
				{
					ListViewItem item = new ListViewItem(info.Name);
					ListViewItem.ListViewSubItem subItem= new ListViewItem.ListViewSubItem();
					subItem.Text = info.EpisodeTitle;
					item.SubItems.Add(subItem);
					//listView1.
					//listView1.Items.Add(item);
				}
			}
		}


        /// <summary>
        /// Web browser navigation handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
		{
			if (e.Url == null || e.Url.OriginalString == null)
				return;

			if (e.Url.OriginalString.StartsWith("file://\\pocketpod\\dele?"))
			{
				e.Cancel = true;
				//webBrowser1.Stop();
				//webBrowser1.GoBack();

				string argument = e.Url.OriginalString.Substring(23);
				argument = argument.Replace('/', '\\');
				PodcastList downloadedPodcasts = PodcastList.LoadFromXml(DownloadedPodcastsListPath);
				PodcastInfo tmpInfo = null;
				foreach (PodcastInfo info in downloadedPodcasts.PodcastInfo)
				{
					if (info.FilePath == argument)
					{
						tmpInfo = info;
						break;
					}
				}
				
				// delete the podcast and remove it from the list
				FileInfo fi = new FileInfo(tmpInfo.FilePath);
				if (File.Exists(tmpInfo.FilePath))
					File.Delete(tmpInfo.FilePath);
				
				downloadedPodcasts.RemoveItem(tmpInfo);
				downloadedPodcasts.SaveToXml(DownloadedPodcastsListPath);

				// refresh display
				DisplayDownloadedPodcasts();
			}
		}
        /*
///<summary>
/// initialize source that grid is displaying for
///</summary>
private bool InitializeControls(DataTable testTable)
{
    if (testTable != null)
    {
        dataPPlist.DataSource = testTable;
        return true;
    }
    else return false;
}*/

        /*
///<summary>
///   - Read a podcast list from a XML file and put it into a datagrid<br/>
///   - Parameter: XmlLoc - location of the xml file<br/>
/// Return true on success, false otherwise<br/>
///</summary>
private bool ReadXml(string xmlLoc)
{
    DataSet testData = new DataSet();
    DataTable testTable = new DataTable(TableName);
    testTable.Columns.Add(new DataColumn(NameCol, typeof(System.String)));
    testTable.Columns.Add(new DataColumn(DescCol, typeof(System.String)));
    testTable.Columns.Add(new DataColumn(CatCol, typeof(System.String)));
    testTable.Columns.Add(new DataColumn(RatCol, typeof(System.Double)));
    testTable.Columns.Add(new DataColumn(FileCol, typeof(System.String)));

    if (File.Exists(xmlLoc))
    {
        PodcastList podcast;
        XmlSerializer serializer = new XmlSerializer(typeof(PodcastList));
        TextReader tr = new StreamReader(xmlLoc);
        try
        {
            podcast = (PodcastList)serializer.Deserialize(tr);
        }
        catch
        {
            return false;
        }
        tr.Close();
        int count = podcast.CountItem();
        PodcastInfo temp;
        DataRow newRow;
        for (int i = 0; i < count; i++)
        {
            temp = podcast.PodcastInfo[i];
            newRow = testTable.NewRow();
            newRow[NameCol] = temp.Name;
            newRow[DescCol] = temp.Description;
            newRow[RatCol] = temp.Ratings;
            newRow[CatCol] = temp.Category;
            newRow[FileCol] = temp.FilePath;
            testTable.Rows.Add(newRow);
        }
        testData.Tables.Add(testTable);
        testTable.AcceptChanges();
        if (InitializeControls(testTable))
            return true;
        else
            return false;
                   
    }
    else
        return false;
}*/


        /*
        ///<summary>
        ///   - Read a list of keywords from a text box and querie it in the Database<br/>
        /// Return int as a flag:<br/>
        ///  1: No keywords enterred<br/>
        ///  2: Too many keywords<br/>
        ///  3: General error with search, i.e. cannot connect to internet<br/>
        ///  4: No matching podcasts found<br/>
        ///  5: Success<br/>
        ///</summary>
        private int Search()
        {
            toolStripProgressBar1.Visible = true;
            net.hlady.pocketpodcasts.NameDescRow[] ndr;
            searcher = new Searcher();
            int foundPodcasts;
            PodcastList myList = new PodcastList();
            net.hlady.pocketpodcasts.PodcastRow PodRow;
            string xmlLoc = @"\Storage Card\podcastlist.xml";

            //parse the keyword list from the textbox
            string[] keywords = SearchBox.Text.Split(' ');

            //check if there was anything in the textbox
            if (SearchBox.Text.Length==0)
            {
                toolStripProgressBar1.Visible = false;
                if (!UnderTest)
                    MessageBox.Show("Please enter a keyword");
                return 1;
            }

            //checks if there are to many keywords
            if (keywords.Length > MaxKeywords)
            {
                toolStripProgressBar1.Visible = false;
                if (!UnderTest)
                    MessageBox.Show(ErrKeywords);
                return 2;
            }

            // retrieve search results from web service
            try
            {
                ndr = searcher.SearchByKeyword(SearchBox.Text.Split(' '), 0, 10);
            }
            
            //checks for parse error
            catch (Exception ex)
            {
                toolStripProgressBar1.Visible = false;
                if (!UnderTest)
                    MessageBox.Show(ex.Message);
                return 3;
            }

            toolStripProgressBar1.Visible = false;

            //checks if anything was found
            foundPodcasts = ndr.Length;
            if (foundPodcasts == 0)
            {
                if (!UnderTest)
                    MessageBox.Show("No Podcast Found");
                return 4;
            }
            else
            {
                //if so, load into xml file and print to screen
                WebFunc = new net.hlady.pocketpodcasts.ppWSDL();
                for (int i = 0; i < foundPodcasts; i++)
                {

                    PodRow = WebFunc.GetPodcastInfoByID(ndr[i].podcastID);
                    myList.AddItem(new PodcastInfo(PodRow.title, PodRow.description, PodRow.category, PodRow.globalRatingValue, @"""\Storage Card\empty.mp3"""));
                }
                WriteXml(myList);
                ReadXml(xmlLoc);
            }
            return 5;
        }*/

        /*
///<summary>
///   - click handler for button1 (Play).  Plays relevant audio file<br/>
///   - located at FileLoc[intIndex]<br/>
///</summary>
private void bntPlay_Click_1(object sender, EventArgs e)
{
    int index;
    FileLoc = new string[10];
    index = dataPPlist.CurrentCell.RowNumber;
    // Since download podcast has not be implemented. A fake list of mp3 file is used.
    FileLoc[0] = @"""\Storage Card\ending.mp3""";
    for (int i = 1; i <= 9; i++)
    {
        FileLoc[i] = @"""\Storage Card\empty.mp3""";
    }

    if (index >= 0)
    {
        if (FileLoc != null)
        {
            System.Diagnostics.Process.Start(@"Windows\wmplayer.exe", FileLoc[index]);
        }
        else
        {
            MessageBox.Show("No Availaible Podcast");
        }
    }
    else
    {
        //user did not select a row
        MessageBox.Show("Select a podcast");
    }
}*/

        /*
        ///<summary>
        ///   - click handler for btnSearch_Click (Search)<br/>
        ///   - Queries Database for podcasts with matching keywords<br/>
        ///</summary>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }*/

        /*
        ///<summary>
        ///   - Test Search (Iteration 2)
        ///   - click handler for btnSearch_Click (Test Search)<br/>
        ///   - For testing/debugging purposes.<br/>
        ///   - Queries Database for podcasts with matching keywords<br/>
        ///   - Tests for empty case, too many keywords, no results, and success scenario<br/>
        ///</summary>
        private void bntTestSearch_Click(object sender, EventArgs e)
        {
            int retval;
            UnderTest = true;
            string result = "";
            SearchBox.Text = "";
            retval = Search();

            if (retval == 1)
                result=result+"Empty case passed!\n";
            else
                result = result + "Empty case failed!\n";
            SearchBox.Text = "0 1 2 3 4 5 6 7 8 9 10";
            retval = Search();
            if (retval == 2)
                result = result + "Max Entries + 1 case passed!\n";
            else
                result = result + "Max Entries + 1 case failed!\n";
            SearchBox.Text = "Please Wait...";
            retval = Search();
            if (retval == 4)
                result = result + "No podcasts case passed!\n";
            else
                result = result + "No podcasts case failed!\n";
            SearchBox.Text = "tech";
            retval = Search();
            if (retval == 5)
                result = result + "Success case passed!\n";
            else
                result = result + "Success case failed!\n";
            UnderTest = false;
            MessageBox.Show(result);
        }*/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Up))
            {
                // Up
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down))
            {
                // Down
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left))
            {
                // Left
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right))
            {
                // Right
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter))
            {
                // Enter
            }

        }
    }
}